package com.huluobo.a2307douyindemo.live

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Intent
import android.util.Log
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.view.animation.AnimationUtils
import android.widget.ImageView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2307douyindemo.R
import com.huluobo.a2307douyindemo.adapter.YellowCartAdapter
import com.huluobo.a2307douyindemo.adapter.GiftAdapter
import com.huluobo.a2307douyindemo.adapter.MessageAdapter
import com.huluobo.a2307douyindemo.databinding.ActivityLiveBinding
import com.huluobo.a2307douyindemo.shop.DetailActivity
import com.huluobo.a2307douyindemo.utils.ImageUtils
import com.huluobo.a2307douyindemo.utils.pay.PayActivity
import com.huluobo.lib_base.bean.GiftBean
import com.huluobo.lib_base.bean.MessageEntity
import com.huluobo.lib_base.bean.Money
import com.huluobo.lib_base.bean.VideoBean
import com.huluobo.lib_base.event.MessageEvent
import com.huluobo.lib_base.mvvm.BaseActivity
import com.huluobo.lib_base.net.Const
import com.hyphenate.EMCallBack
import com.hyphenate.EMChatRoomChangeListener
import com.hyphenate.EMMessageListener
import com.hyphenate.EMValueCallBack
import com.hyphenate.chat.EMChatRoom
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.hyphenate.chat.EMTextMessageBody
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import org.greenrobot.eventbus.EventBus
import top.littlefogcat.danmakulib.danmaku.Danmaku
import top.littlefogcat.danmakulib.danmaku.DanmakuManager

@AndroidEntryPoint
class LiveActivity : BaseActivity<ActivityLiveBinding, LiveViewModel>() {
    private lateinit var videoBean: VideoBean
    private lateinit var giftAdapter: GiftAdapter
    private lateinit var giftBean: GiftBean
    private lateinit var money: Money
    private lateinit var messageAdapter: MessageAdapter
    private lateinit var yellowCartAdapter: YellowCartAdapter

    //只要进入当前页面就查询一次余额
    override fun onResume() {
        super.onResume()
        //通过username发起查询余额
        vm.queryMoney(SPUtils.getInstance().getString(Const.PARAM_USERNAME))
    }

    override fun initData() {

        vm.queryMoneySuccess.observe(this) {
            money = it
            binding.liveUserMoneyTv.text = "余额:${money.money}抖币"
        }
        vm.followAuthSuccess.observe(this) {
            ToastUtils.showLong(it)
            binding.liveFollowBtn.text = "已关注"
            binding.liveFollowBtn.setBackgroundResource(R.drawable.shape_alpha_black)
            videoBean.guanzhu = 1
        }

        vm.unFollowSuccess.observe(this) {
            ToastUtils.showLong(it)
            binding.liveFollowBtn.text = "关注"
            binding.liveFollowBtn.setBackgroundResource(R.drawable.shape_red)
            videoBean.guanzhu = 0
        }

        vm.getGiftSuccess.observe(this) {
            giftAdapter.data.clear()
            giftAdapter.data.addAll(it)
            giftAdapter.notifyDataSetChanged()
        }

        vm.updateMoneySuccess.observe(this) {
            Log.e("TagA", it)
        }

        vm.getGoodsSuccess.observe(this) {
            yellowCartAdapter.data.clear()
            yellowCartAdapter.data.addAll(it)
            yellowCartAdapter.notifyDataSetChanged()
        }
    }

    override fun initView() {
        videoBean = intent.getSerializableExtra(Const.KEY_VIDEO_BEAN) as VideoBean
        binding.livePlayer.backButton.visibility = View.GONE
        binding.livePlayer.setUp(videoBean.videopath, true, "")

        ImageUtils.loadCircleImage(this, videoBean.headpath, binding.liveUserIconIv)
        binding.liveUsernameTv.text = videoBean.authname

        binding.liveFollowBtn.text = if (videoBean.guanzhu == 0) "关注" else "已关注"
        binding.liveFollowBtn.setBackgroundResource(if (videoBean.guanzhu == 0) R.drawable.shape_red else R.drawable.shape_alpha_black)
        binding.liveLikeCountTv.text = "${videoBean.like_count}人喜欢"

        binding.liveFollowBtn.setOnClickListener {
            val map = mutableMapOf<String, String>()
            map[Const.PARAM_AUTH_NAME] = videoBean.authname
            val json = Gson().toJson(map)
            val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
            if (videoBean.guanzhu == 0) {
                //触发关注的方法
                vm.followAuth(body)
            } else {
                //触发取消关注的方法
                vm.unFollowAuth(body)
            }
        }

        //给点赞View添加资源图片
        binding.liveLikeView.addLikeImages(
            R.drawable.fav_0,
            R.drawable.fav_1,
            R.drawable.fav_2,
            R.drawable.fav_3,
            R.drawable.fav_4,
            R.drawable.fav_5
        )

        //点击点赞按钮时
        binding.liveLikeIv.setOnClickListener {
            //展示飘心动画
            binding.liveLikeView.addFavor()
        }

        binding.liveDanmuIv.setOnClickListener {
            binding.liveDanmuLayoutLl.visibility = View.VISIBLE
        }

        binding.liveDanmuSendIv.setOnClickListener {
            //获取弹幕内容
            val danmuString = binding.liveDanmuEt.text.toString()
            if (danmuString.isNotEmpty()) {
                //生成一条弹幕
                val danmuku = Danmaku()
                //设置弹幕文本
                danmuku.text = danmuString
                //设置弹幕大小
                danmuku.size = 30
                //初始化弹幕,添加弹幕的位置View
                DanmakuManager.getInstance().init(this, binding.liveDanmuView)
                //发送弹幕
                DanmakuManager.getInstance().send(danmuku)

                //清空弹幕输入框
                binding.liveDanmuEt.text.clear()
                //隐藏弹幕输入布局
                binding.liveDanmuLayoutLl.visibility = View.GONE
            } else {
                ToastUtils.showLong("弹幕内容不能为空")
            }
        }

        //初始化礼物列表
        binding.liveGiftRv.layoutManager = GridLayoutManager(this, 5)
        giftAdapter = GiftAdapter()
        binding.liveGiftRv.adapter = giftAdapter

        //当选中礼物时,给选中礼物的图片和名字赋值
        giftAdapter.setOnItemClickListener { adapter, view, position ->
            giftBean = giftAdapter.data[position]
            ImageUtils.loadImage(this, giftBean.giftpath, binding.liveGiftSelectIv)
            binding.liveGiftNameTv.text = giftBean.giftname
        }

        //点击礼物图标,展示礼物布局
        binding.liveGiftIv.setOnClickListener {
            binding.liveGiftCl.visibility = View.VISIBLE
            vm.getGift()
        }

        //礼物列表关闭
        binding.liveCloseTv.setOnClickListener {
            binding.liveGiftCl.visibility = View.GONE
        }

        binding.liveGiftSendBtn.setOnClickListener {
            sendGift()
        }

        binding.livePayBtn.setOnClickListener {
            val intent = Intent(this, PayActivity::class.java)
            startActivity(intent)
        }

        //点击展示聊天室的输入框
        binding.liveInputTv.setOnClickListener {
            binding.liveChatRoomLayoutLl.visibility = View.VISIBLE
        }

        //初始化聊天列表
        messageAdapter = MessageAdapter()
        binding.liveChatRoomRv.layoutManager = LinearLayoutManager(this)
        binding.liveChatRoomRv.adapter = messageAdapter

        //初始化聊天室
        initChatRoom()

        //点击聊天内容发送按钮
        binding.liveChatRoomSendIv.setOnClickListener {
            //聊天室假效果
//            val msg = MessageEntity(
//                SPUtils.getInstance().getString(Const.PARAM_USERNAME),
//                binding.liveChatRoomEt.text.toString()
//            )
//            messageAdapter.data.add(msg)
//            messageAdapter.notifyDataSetChanged()
//
//            //设置rv滚动到最后
//            binding.liveChatRoomRv.scrollToPosition(messageAdapter.data.size - 1)
//            //清空聊天输入框
//            binding.liveChatRoomEt.text.clear()
//            binding.liveChatRoomLayoutLl.visibility = View.GONE

            sendMessage()
        }

        //小黄车点击事件
        binding.liveCartIv.setOnClickListener {
            showCart()
        }

        binding.liveCloseIv.setOnClickListener {
            closeCart()
        }
    }

    //关闭小黄车布局
    private fun closeCart() {
        val animOut = AnimationUtils.loadAnimation(this, R.anim.anim_out)
        animOut.duration = 500
        animOut.interpolator = AccelerateInterpolator()
        animOut.setAnimationListener(object : AnimationListener {
            override fun onAnimationStart(animation: Animation?) {
            }

            override fun onAnimationEnd(animation: Animation?) {
                binding.liveCartCl.visibility = View.GONE
            }

            override fun onAnimationRepeat(animation: Animation?) {
            }
        })
        binding.liveCartCl.startAnimation(animOut)
    }

    //打开小黄车布局
    private fun showCart() {
        vm.getGoods(1, 20)
        binding.liveCartCl.visibility = View.VISIBLE
        val animIn = AnimationUtils.loadAnimation(this, R.anim.anim_in)
        animIn.duration = 500
        animIn.interpolator = AccelerateInterpolator()
        binding.liveCartCl.startAnimation(animIn)

        binding.liveCartRv.layoutManager = GridLayoutManager(this, 2)
        yellowCartAdapter = YellowCartAdapter()
        binding.liveCartRv.adapter = yellowCartAdapter
        yellowCartAdapter.setOnItemClickListener { adapter, view, position ->
            val goodsId = yellowCartAdapter.data[position].id
            val intent = Intent(this, DetailActivity::class.java)
            intent.putExtra(Const.PARAM_GOODS_ID, goodsId)
            startActivity(intent)
        }

    }

    //发送消息
    private fun sendMessage() {
        if (binding.liveChatRoomEt.text.toString().isNotEmpty()) {
//            if (binding.liveChatRoomEt.text.toString() == "爱你") {
//                binding.liveRedHeart.visibility = View.VISIBLE
//                binding.liveRedHeart.start()
//            }
            //构建一条发送的消息,第一个参数是消息内容,第二个参数是聊天室id
            val emMessage = EMMessage.createTextSendMessage(binding.liveChatRoomEt.text.toString(), Const.CHAT_ROOM_ID)
            //设置消息类型为聊天室类型
            emMessage.chatType = EMMessage.ChatType.ChatRoom
            //通过环信发送消息
            EMClient.getInstance().chatManager().sendMessage(emMessage)
            emMessage.setMessageStatusCallback(object : EMCallBack {
                override fun onSuccess() {
                    //发送消息成功,添加数据源,刷新适配器
                    val messageEntity = MessageEntity(
                        EMClient.getInstance().currentUser,
                        binding.liveChatRoomEt.text.toString()
                    )
                    //添加数据源
                    messageAdapter.data.add(messageEntity)
                    runOnUiThread {
                        //刷新适配器
                        messageAdapter.notifyDataSetChanged()
                        //滚动到最下方
                        binding.liveChatRoomRv.scrollToPosition(messageAdapter.data.size - 1)
                        binding.liveChatRoomEt.text.clear()
                        binding.liveChatRoomLayoutLl.visibility = View.GONE
                    }
                }

                override fun onError(code: Int, error: String?) {
                }
            })

        } else {
            ToastUtils.showLong("发送消息内容不能为空")
        }
    }

    //初始化聊天室
    private fun initChatRoom() {
        //聊天室添加监听器需要2种,一种是消息接受监听器,另一个是进入和退出聊天室的监听器
        EMClient.getInstance().chatManager().addMessageListener(messageListener)
        EMClient.getInstance().chatroomManager().addChatRoomChangeListener(chatRoomListener)
        //初始化时,加入聊天室
        EMClient.getInstance().chatroomManager().joinChatRoom(Const.CHAT_ROOM_ID, object : EMValueCallBack<EMChatRoom> {
            override fun onSuccess(value: EMChatRoom?) {
                Log.e("TagA", "加入聊天室成功")
            }

            override fun onError(error: Int, errorMsg: String?) {
                Log.e("TagA", "加入聊天室失败:$error,msg:$errorMsg")
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        //退出聊天室
        EMClient.getInstance().chatroomManager().leaveChatRoom(Const.CHAT_ROOM_ID)
        //移除消息监听器
        EMClient.getInstance().chatManager().removeMessageListener(messageListener)
        EMClient.getInstance().chatroomManager().removeChatRoomListener(chatRoomListener)

        //EventBus例子
        //发送关闭直播间事件通知
        EventBus.getDefault().post(MessageEvent("关掉了直播间"))
    }

    //用于接收消息
    private val messageListener = EMMessageListener {
        //接收到消息时,需要遍历每一条消息的内容,并添加到数据源
        it.forEach { emMessage ->
            //解析消息中的用户
            val user = emMessage.userName
            //解析消息内容
            val content = (emMessage.body as EMTextMessageBody).message
            //将解析到的内容添加到实体类中
            val messageEntity = MessageEntity(user, content)
            //追加数据源
            messageAdapter.data.add(messageEntity)
            runOnUiThread {
                //刷新适配器
                messageAdapter.notifyDataSetChanged()
                //滚动到最下方
                binding.liveChatRoomRv.scrollToPosition(messageAdapter.data.size - 1)
            }
        }
    }

    //用于监听用户进入和退出
    private val chatRoomListener = object : EMChatRoomChangeListener {
        override fun onChatRoomDestroyed(roomId: String?, roomName: String?) {
        }

        override fun onMemberJoined(roomId: String?, participant: String?) {
            //由于 object : EMChatRoomChangeListener  在监听器中,一般环信的监听器都是在子线程中的
            //需要更新UI的位置时,要切换到主线程
            runOnUiThread {
                messageAdapter.data.add(MessageEntity("系统", "${participant}加入直播间"))
                messageAdapter.notifyDataSetChanged()
            }
        }

        override fun onMemberExited(roomId: String?, roomName: String?, participant: String?) {
            runOnUiThread {
                messageAdapter.data.add(MessageEntity("系统", "${participant}退出直播间"))
                messageAdapter.notifyDataSetChanged()
            }
        }

        override fun onRemovedFromChatRoom(reason: Int, roomId: String?, roomName: String?, participant: String?) {
        }

        override fun onMuteListAdded(chatRoomId: String?, mutes: MutableList<String>?, expireTime: Long) {
        }

        override fun onMuteListRemoved(chatRoomId: String?, mutes: MutableList<String>?) {
        }

        override fun onWhiteListAdded(chatRoomId: String?, whitelist: MutableList<String>?) {
        }

        override fun onWhiteListRemoved(chatRoomId: String?, whitelist: MutableList<String>?) {
        }

        override fun onAllMemberMuteStateChanged(chatRoomId: String?, isMuted: Boolean) {
        }

        override fun onAdminAdded(chatRoomId: String?, admin: String?) {
        }

        override fun onAdminRemoved(chatRoomId: String?, admin: String?) {
        }

        override fun onOwnerChanged(chatRoomId: String?, newOwner: String?, oldOwner: String?) {
        }

        override fun onAnnouncementChanged(chatRoomId: String?, announcement: String?) {
        }
    }

    //发送礼物
    private fun sendGift() {
        //当余额不够支付选中礼物价格时
        if (money.money < giftBean.price) {
            ToastUtils.showLong("用户余额不足,请充值")
            return
        }
        //创建新的余额,等于当前余额减去礼物价格
        val newMoney = money.money - giftBean.price
        //赋值最新的余额到页面上
        binding.liveUserMoneyTv.text = "余额:${newMoney}抖币"
        //把最新的余额更新到money中
        money.money = newMoney
        //更新数据库
        vm.updateMoney(money)

        //创建一个ImageView
        val giftAnimView = ImageView(this)
        //设置imageView的大小
        val params = ConstraintLayout.LayoutParams(200, 200)
        giftAnimView.layoutParams = params

        //将ImageView添加到最大的布局上
        binding.liveRootCl.addView(giftAnimView)
        //设置ImageView的图片资源
        ImageUtils.loadImage(this, giftBean.giftpath, giftAnimView)

        //获取整个屏幕最大布局的宽高
        val screenWidth = binding.liveRootCl.measuredWidth
        val screenHeight = binding.liveRootCl.measuredHeight

        //影响高度的动画
        val translationY = ObjectAnimator.ofFloat(
            giftAnimView,
            "translationY",
            screenHeight.toFloat(),
            (screenHeight / 5 * 3).toFloat(),
            (screenHeight / 3).toFloat(),
            (screenHeight / 2).toFloat(),
            (screenHeight / 3 * 2).toFloat(),
            (screenHeight / 2).toFloat()
        )

        val translationX = ObjectAnimator.ofFloat(
            giftAnimView,
            "translationX",
            (screenWidth / 2).toFloat(),
            0f,
            (screenWidth / 2).toFloat(),
            screenWidth.toFloat(),
            (screenWidth / 2).toFloat(),
            (screenWidth / 3).toFloat(),
        )

        val rotation = ObjectAnimator.ofFloat(giftAnimView, "rotation", 0f, 1800f)
        val scaleX = ObjectAnimator.ofFloat(giftAnimView, "scaleX", 1f, 2f, 1f, 3f, 1f, 2f, 1f)
        val scaleY = ObjectAnimator.ofFloat(giftAnimView, "scaleY", 1f, 2f, 1f, 3f, 1f, 2f, 1f)
        val alpha = ObjectAnimator.ofFloat(giftAnimView, "alpha", 1f, 1f, 1f, 1f, 0f)

        val animatorSet = AnimatorSet()
        animatorSet.duration = 3000
        animatorSet.playTogether(translationX, translationY, rotation, scaleX, scaleY, alpha)
        animatorSet.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationStart(animation: Animator) {
                super.onAnimationStart(animation)
                //动画开始,隐藏礼物布局
                binding.liveGiftCl.visibility = View.GONE
            }

            override fun onAnimationEnd(animation: Animator) {
                super.onAnimationEnd(animation)
                //动画结束,移除掉礼物的View
                binding.liveRootCl.removeView(giftAnimView)
            }
        })
        animatorSet.start()
    }
}